package com.sts.controller;

import com.sts.common.result.Result;
import com.sts.dto.request.LoginRequest;
import com.sts.dto.request.PasswordUpdateRequest;
import com.sts.dto.request.ReTokenReq;
import com.sts.dto.request.RegisterRequest;
import com.sts.dto.response.LoginResponse;
import com.sts.dto.response.ReTokenResp;
import com.sts.dto.response.UserRegisterResp;
import com.sts.dto.response.UserInfoResp;
import com.sts.service.AuthService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.naming.AuthenticationException;
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {
    // 将原来的字段注入
    /*@Autowired private AuthService authService;*/
    //构造函数注入：
   private final AuthService authService;
    @Autowired
    public AuthController(AuthService authService) {
        this.authService = authService;
    }
    /**
    * 用户注册接口
    * @param registerRequest 注册参数
    * @return 注册结果
    */
    @PostMapping("/register")
    public Result<UserRegisterResp> register(@Validated @RequestBody RegisterRequest registerRequest){
        UserRegisterResp userRegisterResp =authService.register(registerRequest);
        return Result.success(userRegisterResp);
    }
/**
 * 用户登录接口
 * @param logreq 登录请求参数（用户名和密码）
 * @return 包含JWT Token的响应结果
 */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Validated @RequestBody LoginRequest logreq) {
        LoginResponse response = authService.login(logreq);
        return Result.success(response).message("登录成功");

    }
    /**
     * 获取用户信息
     */
    @PreAuthorize("hasAnyRole('CUSTOMER', 'EMPLOYEE', 'ADMIN')")
    @GetMapping("/me")
    public Result<UserInfoResp> userIfo(@RequestHeader(name = "Authorization")String token) {
        return Result.success(authService.getUserInfo(token));
    }
    /**
     * 刷新Token
     * “刷新 Token 像一把‘后台钥匙’：前台钥匙（Access Token）丢了只损失 5 分钟，后台钥匙（Refresh Token）丢了能立刻换掉整把锁
     */
    @PostMapping("/refresh")
    public Result<ReTokenResp> refersh(@Valid @RequestBody ReTokenReq reTokenReq) {
        ReTokenResp p =authService.refresh(reTokenReq.getRefreshToken());
        return Result.success(p);
    }
    /**
     * 退出登录
     * 真正的安全边界在服务端，而不是在客户端
     *      * 前端删掉 token ≠ 服务端失效
     *      * 前端删 token 只是“掩耳盗铃”，服务端让 token 失效才是“真退出”。
     */
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization")String authorization){
        log.info("[用户退出] token={}", authorization.substring(0,10)+"...");
        authService.logout(authorization);
        return Result.success().message("退出成功");
    }
    /**
     * 修改密码
     */
    @PreAuthorize("isAuthenticated()")
    @PutMapping("/password")
    public Result<Void> updatePwd(@RequestHeader("Authorization") String authorization, @Valid @RequestBody PasswordUpdateRequest req){
        log.info("[修改密码] token={}", authorization.substring(0,10)+"...");
        authService.updatePwd(authorization, req);
        return Result.success().message("密码已更新，请重新登录");
    }

}
